package com.example.k12.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.os.CountDownTimer
import android.view.View
import com.example.k12.R
import com.example.k12.base.BaseDialog
import com.example.k12.bean.PayRes
import com.example.k12.databinding.DialogPayResultBinding

class PayResultDialog(context: Context, private val payRes: PayRes) :
    BaseDialog<DialogPayResultBinding>(context) {
    private var countDownTimer: CountDownTimer? = null
    override fun getWidth(): Int {
        return context.resources.getDimensionPixelSize(R.dimen.dp400)
    }


    override fun initData() {

        // 支付结果UI处理
        if (payRes.code == 0) {
            mBinding.tvPaymentStatus.text = "成功支付：${payRes.data?.orderAmount}"
            mBinding.tvPaymentHint.visibility = View.GONE
            mBinding.ivLoading.setImageResource(R.mipmap.sucess)
            mBinding.llPaying.visibility = View.VISIBLE
            mBinding.tvUserName.text = payRes.data?.studentName
            mBinding.tvAmount.text = "余额：${payRes.data?.balanceAfter}"
            startCountdown(4000)
        } else {
            mBinding.tvPaymentStatus.text = "支付失败"
            mBinding.llPaying.visibility = View.GONE
            mBinding.ivLoading.setImageResource(R.mipmap.failure)
            mBinding.tvPaymentHint.visibility = View.VISIBLE
            mBinding.tvPaymentHint.text = payRes.msg
            startCountdown(6000)
        }
        mBinding.tvPaymentTimer.setOnClickListener {
            countDownTimer?.cancel()
            dismiss()
        }
    }


    private fun startCountdown(totalTime: Long) {
        countDownTimer = object : CountDownTimer(totalTime, 1000) {
            @SuppressLint("SetTextI18n")
            override fun onTick(millisUntilFinished: Long) {
                val secondsRemaining = millisUntilFinished / 1000
                mBinding.tvPaymentTimer.text = "我知道了(${secondsRemaining}s)"
            }

            override fun onFinish() {
                dismiss()// 关闭 dialog
            }
        }.start()
    }

}
